package SGEngine

import (
	"bufio"
	//"fmt"
	"github.com/gl"
	"os"
	"strconv"
	"strings"
)

type Atlas struct {
	Tex           *ACTexture
	AtlasName     string
	width, height int
	SpriteDatas   map[string]*AtlasSpriteData
}

type AtlasSpriteData struct {
	SpriteName     string
	Xpos, Ypos     int
	Width, Height  int
	TexBuffer      gl.Buffer
	ReferenceCount uint32
}

func NewAtlas(name, imgname string) *Atlas {
	RAtlas := LoadAtlas(name)
	RAtlas.Tex = ACTextureMgr.LoadTexture(imgname)
	return RAtlas
}

func LoadAtlas(name string) *Atlas {
	f, _ := os.Open(name + ".txt")
	rf := bufio.NewReader(f)
	RAtlas := new(Atlas)
	RAtlas.SpriteDatas = make(map[string]*AtlasSpriteData)
	//Read Head
	str, _ := rf.ReadString('~')
	Arr := strings.Split(str, "\n")
	RAtlas.width, _ = strconv.Atoi(Arr[1][2:len(Arr[1])])
	RAtlas.height, _ = strconv.Atoi(Arr[2][2:len(Arr[2])])
	//Read Images
	for {
		linstr, err := rf.ReadString('~')
		if err != nil {
			break
		}
		RData := ReadAtlasImages(linstr)
		RAtlas.SpriteDatas[RData.SpriteName] = RData
	}
	//fmt.Println(RAtlas)
	return RAtlas
}
func ReadAtlasImages(str string) *AtlasSpriteData {
	RSpriteData := new(AtlasSpriteData)
	Arr := strings.Split(str, "\n")
	NumArr := strings.Split(Arr[2], " ")

	RSpriteData.SpriteName = Arr[1][2:len(Arr[1])]
	RSpriteData.Xpos, _ = strconv.Atoi(NumArr[1])
	RSpriteData.Ypos, _ = strconv.Atoi(NumArr[2])
	RSpriteData.Width, _ = strconv.Atoi(NumArr[3])
	RSpriteData.Height, _ = strconv.Atoi(NumArr[4])
	return RSpriteData
}
